import * as api from './api';
import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess,
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import {PAGE} from '../constants';
import {conventTableCondition, formatAmount} from '../utils';
import moment from 'moment';

/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = (data, conditions) => ({
    type: GET_INIT_SUCCESS,
    data,
    conditions
});
export const getInitDataFail = message => ({
    type: GET_INIT_FAIL,
    message
});

//获取初始化数据和权限

export const getInitData = () => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.initQuery().then(res => {
        if(res.ok) 
            dispatch(getInitDataSuccess(res.data));
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(PAGE_CODE).then(res => {
        if(res.isOk)
            dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else
            dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};
/*==============================查询列表================================= */
export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';

export const getListBegin = () => ({
    type: GET_LIST_BEGIN,
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition,
});
export const getListFail = () => ({
    type: GET_LIST_FAIL
});
const conventDate = (condition = {}) => {
    const {createTime, countryId, dealerCode, marketDepartmentName, dealerName, ...others} = condition;
    if(!createTime || createTime.length === 0) return others;
    return {
        ...others,
        beginCreateTime: moment(createTime[0]).toISOString(),
        endCreateTime: moment(createTime[1]).toISOString(),
    };
};
const conventConfirmDate = (condition = {}) => {
    const {confirmTime, countryId, dealerCode, marketDepartmentName, dealerName, ...others} = condition;
    if(!confirmTime || confirmTime.length === 0) return others;
    return {
        ...others,
        confirmBeginTime: moment(confirmTime[0]).toISOString(),
        confirmEndTime: moment(confirmTime[1]).toISOString(),
    };
};
//获取列表
export const getList = condition => dispatch => {
    if(!condition)
        return;
    const queryCondition = conventTableCondition(conventConfirmDate(conventDate(condition)));
    dispatch(getListBegin());
    return api.getList(queryCondition).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
    });
};
//按钮搜索
export const querySearch = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    condition.pageIndex = PAGE.index;
    dispatch(getList(condition));
};
//分页排序搜索
export const tableSearch = page => (dispatch, getState) => {
    const query = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

/*==============================查询action================================= */
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
/*==============================重置查询条件================================= */
export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL
});

/*==============================新增修改action================================= */
export const onSubmit = (data, details) => () =>
    //增加判断必填字段
    data.id ? api.modifyOrder(data.id, {
        rowVersion: data.rowVersion,
        countryOfOrigin: data.countryOfOrigin ? data.countryOfOrigin : null,
        countryOfDestination: data.countryOfDestination ? data.countryOfDestination : null,
        CNPJ: data.cnpj ? data.cnpj : null,
        contact: data.contact ? data.contact : null,
        tradeMethodId: data.tradeMethodId ? data.tradeMethodId : null,
        salesOrderPriceTerms: data.salesOrderPriceTerms ? data.salesOrderPriceTerms : null,
        paymentType: data.paymentType ? data.paymentType : null,
        shipmentAmount: data.shipmentAmount ? data.shipmentAmount : null,
        insuranceAmount: data.insuranceAmount ? data.insuranceAmount : null,
        deliveryTerms: data.deliveryTerms ? data.deliveryTerms : null,
        payableAccount: data.payableAccount ? data.payableAccount : null,
        carrierId: data.carrierId ? data.carrierId : null,
        shippingPortId: data.shippingPortId ? data.shippingPortId : null,
        destinationPort: data.destinationPort ? data.destinationPort : null,
        commodity: data.commodity ? data.commodity : null,
        bankId: data.bankId ? data.bankId : null,
        currency: data.currency ? data.currency : null,
        contactNumber: data.contactNumber ? data.contactNumber : null,
        TELEX: data.telex ? data.telex : null,
        remark: data.remark ? data.remark : null,
        batchNumber: data.batchNumber ? data.batchNumber : null,
        address: data.address ? data.address : null,
        certificationAmount: data.certificationAmount,
        // eslint-disable-next-line no-unneeded-ternary
        ifUseBatchNumberToPrint: data.ifUseBatchNumberToPrint === 1 ? true : false,
        estimatedDeliveryDate: data.estimatedDeliveryDate,
        validity: data.validity,
        packing: data.packing,
        isCBU: true,
        saleProformaPartDetails: [],
        saleProformaInvoiceDetails: details.map(v => ({
            saleOrderId: v.saleOrderId,
            quantity: v.quantity ? v.quantity : null,
            price: v.price ? v.price : null,
            saleOrderDetailId: v.saleOrderDetailId ? v.saleOrderDetailId : null,
            remark: v.remark ? v.remark : null,
            unitShipmentAmount: v.unitShipmentAmount ? (v.unitShipmentAmount).toFixed(2) : null,
            // unitInsuranceAmount: v.unitInsuranceAmount ? v.unitInsuranceAmount : null,
            unitVolume: v.unitVolume ? v.unitVolume : null,
            containerNumber: v.containerNumber ? v.containerNumber : null,
            productGroupId: v.productGroupId,
            productId: v.productId
        })),
    }).then(res => ({success: res.ok})) : api.newOrder({
        isCBU: true,
        brandId: data.brandId ? data.brandId : null,
        dataSource: data.dataSource,
        dealerId: data.dealerId ? data.dealerId : null,
        countryOfOrigin: data.countryOfOrigin ? data.countryOfOrigin : null,
        countryOfDestination: data.countryOfDestination ? data.countryOfDestination : null,
        CNPJ: data.cnpj ? data.cnpj : null,
        contact: data.contact ? data.contact : null,
        tradeMethodId: data.tradeMethodId ? data.tradeMethodId : null,
        salesOrderPriceTerms: data.salesOrderPriceTerms ? data.salesOrderPriceTerms : null,
        paymentType: data.paymentType ? data.paymentType : null,
        shipmentAmount: data.shipmentAmount ? data.shipmentAmount : null,
        insuranceAmount: data.insuranceAmount ? data.insuranceAmount : null,
        deliveryTerms: data.deliveryTerms ? data.deliveryTerms : null,
        payableAccount: data.payableAccount ? data.payableAccount : null,
        carrierId: data.carrierId ? data.carrierId : null,
        shippingPortId: data.shippingPortId ? data.shippingPortId : null,
        destinationPort: data.destinationPort ? data.destinationPort : null,
        commodity: data.commodity ? data.commodity : null,
        bankId: data.bankId ? data.bankId : null,
        currency: data.currency ? data.currency : null,
        contactNumber: data.contactNumber ? data.contactNumber : null,
        TELEX: data.telex ? data.telex : null,
        remark: data.remark ? data.remark : null,
        batchNumber: data.batchNumber ? data.batchNumber : null,
        address: data.address ? data.address : null,
        certificationAmount: data.certificationAmount,
        // eslint-disable-next-line no-unneeded-ternary
        ifUseBatchNumberToPrint: data.ifUseBatchNumberToPrint === 1 ? true : false,
        estimatedDeliveryDate: data.estimatedDeliveryDate,
        validity: data.validity,
        packing: data.packing,
        saleProformaPartDetails: [],
        saleProformaInvoiceDetails: details.map(v => ({
            saleOrderId: v.saleOrderId,
            quantity: v.quantity ? v.quantity : null,
            price: v.price ? v.price : null,
            saleOrderDetailId: v.saleOrderDetailId ? v.saleOrderDetailId : null,
            remark: v.remark ? v.remark : null,
            unitShipmentAmount: v.unitShipmentAmount ? (v.unitShipmentAmount).toFixed(2) : null,
            // unitInsuranceAmount: v.unitInsuranceAmount ? v.unitInsuranceAmount : null,
            unitVolume: v.unitVolume ? v.unitVolume : null,
            containerNumber: v.containerNumber ? v.containerNumber : null,
            productGroupId: v.productGroupId,
            productId: v.productId
        })),
    }).then(res => ({success: res.ok}))
;

export const SELECT_DEALER_QUERY = 'SELECT_DEALER_QUERY';
export const selectDealerQuery = data => ({
    type: SELECT_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});

export const SELECT_AREA_QUERY = 'SELECT_AREA_QUERY';
export const selectAreaQuery = data => ({
    type: SELECT_AREA_QUERY,
    data: {
        countryId: data.id,
        country: data.chineseName,
    }
});
export const SELECT_MARKE_QUERY = 'SELECT_MARKE_QUERY';
export const selectMarkeQuery = data => ({
    type: SELECT_MARKE_QUERY,
    data: {
        marketDepartmentId: data.id,
        marketDepartmentName: data.name,
    }
});


